/**
 * Writed by yura and mak
 */

package wz.legend.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;

public class ConfigFileStorage implements FileStorage {

    private static final Logger LOG = Logger.getLogger(ConfigFileStorage.class);

    private String fileName;
    private String encoding;

    public ConfigFileStorage(String fileName) {
        this.fileName = fileName;
    }

    public ConfigFileStorage(String fileName, String encoding) {
        this(fileName);
        this.encoding = encoding;
    }

    public Object loadStream() {
        Reader reader = null;
        try {
            if (new java.io.File(fileName).exists()) {
                if (encoding == null) {
                    reader = new InputStreamReader(
                            new FileInputStream(fileName));
                } else {
                    reader = new InputStreamReader(
                            new FileInputStream(fileName), encoding);
                }
                return new XStream().fromXML(reader);
            }
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    public boolean saveStream(Object object) {
        Writer writer = null;
        try {
            if (encoding == null) {
                writer = new OutputStreamWriter(new FileOutputStream(fileName));
            } else {
                writer = new OutputStreamWriter(new FileOutputStream(fileName),
                        encoding);
            }
            new XStream().toXML(object, writer);
            writer.flush();
            return true;
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
